const app = getApp()
const i18n = require('../../../utils/i18n/index')

Page({
  data: {
    license: '', // 营业执照图片地址
    form: {
      company: '',
      company_en: '',
      company_address: '',
      company_address_en: '',
      contact: '',
      name: '',
      position: '',
      position_en: ''
    },
    locale: 'zh_CN',
    t: {}
  },

  onLoad() {
    this.setI18nData()
  },

  setI18nData() {
    this.setData({
      locale: i18n.getLocale(),
      t: {
        title: i18n.t('mine.join.title'),
        companyName: i18n.t('mine.join.companyName'),
        companyNameEn: i18n.t('mine.join.companyNameEn'),
        companyAddress: i18n.t('mine.join.companyAddress'),
        companyAddressEn: i18n.t('mine.join.companyAddressEn'),
        contactPerson: i18n.t('mine.join.contactPerson'),
        position: i18n.t('mine.profile.position'),
        contactPhone: i18n.t('mine.join.contactPhone'),
        businessScope: i18n.t('mine.join.businessScope'),
        businessScopeEn: i18n.t('mine.join.businessScopeEn'),
        submit: i18n.t('mine.join.submit'),
        companyNamePlaceholder: i18n.t('mine.join.companyNamePlaceholder'),
        companyNameEnPlaceholder: i18n.t('mine.join.companyNameEnPlaceholder'),
        companyAddressPlaceholder: i18n.t('mine.join.companyAddressPlaceholder'),
        companyAddressEnPlaceholder: i18n.t('mine.join.companyAddressEnPlaceholder'),
        contactPersonPlaceholder: i18n.t('mine.join.contactPersonPlaceholder'),
        contactPhonePlaceholder: i18n.t('mine.join.contactPhonePlaceholder'),
        businessScopePlaceholder: i18n.t('mine.join.businessScopePlaceholder'),
        businessScopeEnPlaceholder: i18n.t('mine.join.businessScopeEnPlaceholder'),
        incomplete: i18n.t('mine.join.incomplete'),
        submitSuccess: i18n.t('mine.join.submitSuccess'),
        submitFail: i18n.t('mine.join.submitFail')
      }
    })
  },

  onLanguageChange() {
    this.setI18nData()
  },

  // 表单输入处理
  onInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`form.${field}`]: e.detail.value
    })
  },

  // 选择营业执照
  chooseLicense() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tempFile = res.tempFiles[0]
        this.uploadLicense(tempFile)
      }
    })
  },

  // 上传营业执照
  uploadLicense(file) {
    wx.showLoading({ title: '上传中...' })
    wx.uploadFile({
      url: app.globalData.baseUrl + 'api/upload',
      filePath: file.tempFilePath,
      name: 'file',
      success: res => {
        const data = JSON.parse(res.data)
        if (data.code === 0) {
          this.setData({
            license: data.url || data.data.url
          })
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 预览营业执照
  previewLicense() {
    if (this.data.license) {
      wx.previewImage({
        urls: [this.data.license]
      })
    }
  },

  // 提交表单
  onSubmit() {
    const { form, license } = this.data
    console.log(form)
    // 表单验证
    if (!form.company ||
        !form.contact || !form.name || 
        !form.position) {
      wx.showToast({
        title: this.data.t.incomplete,
        icon: 'none'
      })
      return
    }
    /*if (!license) {
      wx.showToast({
        title: '请上传营业执照',
        icon: 'none'
      })
      return
    }*/

    wx.showLoading({ title: i18n.t('common.loading') })

    wx.request({
      url: app.globalData.baseUrl + 'api/join-union',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      data: { ...form, license },
      success: res => {
        if (res.data.code === 0) {
          wx.showModal({
            title: '提示',  // 模态框标题
            content: this.data.t.submitSuccess,  // 你要显示的长内容
            showCancel: false,  // 是否显示取消按钮
            confirmText: '确定',  // 确认按钮的文字
            success: function(res) {
              if (res.confirm) {
                wx.navigateBack()
              }
            }
          });
        } else {
            wx.showModal({
                title: '提示',  // 模态框标题
                content: this.data.t.submitFail,  // 你要显示的长内容
                showCancel: false,  // 是否显示取消按钮
                confirmText: '确定',  // 确认按钮的文字
                success: function(res) {
                  if (res.confirm) {
                    // 用户点击了确定按钮的回调
                  }
                }
              });
        
        }
      },
      fail: () => {
        wx.showToast({
          title: this.data.t.submitFail,
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 表单验证
  validateForm(formData) {
    const requiredFields = {
      company: '企业名称',
      credit_code: '统一社会信用代码',
      address: '企业地址',
      contact_name: '联系人姓名',
      contact_position: '联系人职务',
      name: '联系人手机号',
      contact_email: '联系人邮箱',
      business: '主营业务'
    }

    for (const [field, label] of Object.entries(requiredFields)) {
      if (!formData[field]) {
        wx.showToast({
          title: `请输入${label}`,
          icon: 'none'
        })
        return false
      }
    }

    if (!this.data.license) {
      wx.showToast({
        title: '请上传营业执照',
        icon: 'none'
      })
      return false
    }

    // 手机号格式验证
    const phoneReg = /^1[3-9]\d{9}$/
    if (!phoneReg.test(formData.name)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return false
    }

    // 邮箱格式验证
    const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    if (!emailReg.test(formData.contact_email)) {
      wx.showToast({
        title: '请输入正确的邮箱',
        icon: 'none'
      })
      return false
    }

    return true
  }
}) 